from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.urls.base import reverse_lazy
from .forms import PubBlogForm
from .models import BlogCategory, Blog, BlogComment
from django.http.response import JsonResponse


# Create your views here.

def index(request):
    return render(request, 'index.html')

def blog_detail(request, id):
    return render(request, 'blog_detail.html')

# 直接使用reverse会报错，因为django在登录判断前可能还没有加载到url
@login_required(login_url = reverse_lazy("zlauth:login"))
def pub_blog(request):
    if request.method == 'GET':
         categories = BlogCategory.objects.all()
         return render(request, 'pub_blog.html', context = {"categories": categories})
    else:
        # 从 AJAX 请求中获取数据
        title = request.POST.get('title')
        content = request.POST.get('content')
        print(title)
        print('content:', content)
        category_id = request.POST.get('category_id')
        user = request.user
        # 验证数据
        if not title or not content or not category_id:
            return JsonResponse({"code": 400, "message": "参数错误"})
        else:
            try:
                category_id = BlogCategory.objects.get(id=category_id)
            except BlogCategory.DoesNotExist:
                return JsonResponse({"code": 400, "message": "分类不存在"})

            # 创建博客
            Blog.objects.create(title=title, content=content, category=category_id, author=user)
            return JsonResponse({"code": 200, "message": "博客发布成功"})